import 'dart:math';

import 'package:flutter/material.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:lib_bt/send/BleSendManager.dart';

class SendProgressDialogUtil {
  static SendProgressDialogUtil? _instance;

  static SendProgressDialogUtil get instance => _instance ??= SendProgressDialogUtil._();

  SendProgressDialogUtil._();

  static CancelFunc? cancelFunc;

  void showDialog() {
    cancelFunc?.call();
    cancelFunc = BotToast.showCustomLoading(
        onClose: () {},
        toastBuilder: (context) {
          return Container(
              decoration: BoxDecoration(color: const Color(0xfffafafa), borderRadius: BorderRadius.circular(10)),
              width: 100,
              height: 100,
              child: ListenableBuilder(
                  listenable: BleSendManager.instance.sendProgressBean,
                  builder: (BuildContext context, Widget? child) {
                    return SendProgressWidget(progress: BleSendManager.instance.sendProgressBean.progress);
                  }));
        });
  }

  void dismissDialog() {
    cancelFunc?.call();
  }
}

class SendProgressWidget extends StatefulWidget {
  final double progress;

  const SendProgressWidget({super.key, required this.progress});

  @override
  State<SendProgressWidget> createState() => _SendProgressWidgetState();
}

class _SendProgressWidgetState extends State<SendProgressWidget> {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      return SizedBox(
          width: constraints.maxWidth,
          height: constraints.maxHeight,
          child: Stack(alignment: Alignment.center, fit: StackFit.expand, children: [
            CustomPaint(painter: YourCustomPainter(progress: widget.progress)),
            Center(
                child: Text("${(widget.progress * 100).toStringAsFixed(0)}%",
                    style: const TextStyle(color: Colors.black, fontSize: 14)))
          ]));
    });
  }
}

double angleToRadians(double angle) {
  return angle * (pi / 180);
}

class YourCustomPainter extends CustomPainter {
  double progress;

  YourCustomPainter({required this.progress});

  @override
  void paint(Canvas canvas, Size size) {
    var width = size.width * 0.8;
    Rect rect = Rect.fromLTWH((size.width - width) / 2, (size.height - width) / 2, width, width);
    Paint paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 6
      ..color = Colors.black12.withAlpha(50);
    canvas.drawArc(rect, 0, angleToRadians(360), false, paint);
    paint.color = Colors.blueGrey;
    canvas.drawArc(rect, angleToRadians(-90), angleToRadians(360 * progress), false, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
